/**
 * 
 */
package com.sample.helper;

import com.google.common.base.Supplier;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.MongoURI;
import java.net.UnknownHostException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Recuperation du serveur mongo.
 */
public class MongoSupplier implements Supplier<DBCollection> {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(MongoSupplier.class);

	/**
	 * Le nom de la base Mongo.
	 */
	private String dbName;
	/**
	 * Le nom de la collection contenue dans la base.
	 */
	private String nameCollection;
	
	private final Mongo mongo;

	/**
	 * Initialise la base mongo.
	 */
	public MongoSupplier(final String uri) {
		this.mongo = initMongo(uri);
		
	}

	/**
	 * @param uri
	 * @return La base Mongo.
	 */
	private static Mongo initMongo(final String uri) {
		try {
			final Mongo mongo = new Mongo(new MongoURI(uri));
			return mongo;
		} catch (UnknownHostException e) {
			LOGGER.warn("foundMongo", e);
		} catch (MongoException e) {
			LOGGER.warn("foundMongo", e);
		}
		return null;
	}

	public DBCollection get() {
		return mongo.getDB(dbName).getCollection(nameCollection);
	}
	
	public MongoSupplier setDbName(String dbName) {
		this.dbName = dbName;
		return this;
	}
	
	public MongoSupplier setNameCollection(String nameCollection) {
		this.nameCollection = nameCollection;
		return this;
	}

}
